package edu.zju.udms.dnavigator.entities.kettle;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import edu.zju.udms.dnavigator.core.entity.AttributeType;
import edu.zju.udms.dnavigator.core.entity.AttributeTypeEnum;
import edu.zju.udms.dnavigator.core.entity.Entity;
import edu.zju.udms.dnavigator.core.entity.GeneralType;
import edu.zju.udms.dnavigator.core.entity.Relation;
import edu.zju.udms.dnavigator.core.repository.Repository;
import edu.zju.udms.dnavigator.entities.mongodb.MongoDBCollection;
import edu.zju.udms.dnavigator.entities.mongodb.MongoDBExtractor;
import edu.zju.udms.dnavigator.entities.mysql.MySQLExtractor;
import edu.zju.udms.dnavigator.entities.mysql.MySQLTable;

public class KettleStep extends Entity{
	/**
	 * 
	 */
	private static final long serialVersionUID = 4373191225471933392L;

	@AttributeType(AttributeTypeEnum.Key)
	public String originalId;
	
	@AttributeType(AttributeTypeEnum.Normal)
	public String transformId;
	@AttributeType(AttributeTypeEnum.Normal)
	public String dbSource;
	@AttributeType(AttributeTypeEnum.Normal)
	public int runTime;
	@AttributeType(AttributeTypeEnum.Normal)
	public String sourceKey;
	
	
	public String dbHost;
	public String dbPort;
	public String dbDatabase;
	public String dbTable;
	public boolean input;
	
	public KettleStep(){}
	
	public KettleStep(String originalId, String name, String sourceKey, String desc, String transformId) {
		super(name, "step:"+name, GeneralType.Step, "Kettle", 0, 0, null, name, desc);
		this.originalId = originalId;
		this.transformId = transformId;
		this.sourceKey = sourceKey;
	}
	
	@Override
	protected List<Relation> advancedAnalyze(Repository repository) {
		if(dbSource == null) {
			return null;
		}
		Map<String, Object> conditions = new HashMap<String, Object>();
		String tableId = null;
		conditions.put("hostName", dbHost+":"+dbPort);
		conditions.put("qualifiedName", dbDatabase+":"+dbTable);

		if(dbSource.equals(MongoDBExtractor.SOURCE)) {
			tableId = repository.filterLastID(MongoDBCollection.class, conditions);
		} else if(dbSource.equals(MySQLExtractor.SOURCE)) {
			tableId = repository.filterLastID(MySQLTable.class, conditions);
		}

		if(tableId != null) {
			List<Relation> res = new ArrayList<Relation>();
			if(input) {
				res.add(new Relation(tableId, getId(), "input"));
			} else {
				res.add(new Relation(getId(), tableId, "output"));
			}
			return res;
		} else {
			return null;
		}
	}

	public String getOriginalId() {
		return originalId;
	}

	public void setOriginalId(String originalId) {
		this.originalId = originalId;
	}

	public String getTransformId() {
		return transformId;
	}

	public void setTransformId(String transformId) {
		this.transformId = transformId;
	}
	
}
